import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    carlist: JSON.parse(localStorage.getItem("cartList")) || []
  },
  mutations: {
    onClick(state, item) {
      var flag = false
      state.carlist.forEach((element) => {
        if (element.good._id == item._id) {
          element.num++
          flag = true
        }
      })
      if (!flag) {
        state.carlist.push({
          good: item,
          num: 1,
          choose: false
        })
      }
      localStorage.setItem("cartList", JSON.stringify(state.carlist))
      console.log(state.carlist);
    },
    change(state, item) {
      state.carlist.forEach((element) => {
        if (element.good._id == item._id) {
          element.choose = !element.choose
        }
      })
      localStorage.setItem("cartList", JSON.stringify(state.carlist))
    },
    allChoose(state, val) {
      state.carlist.forEach((element) => {
        element.choose = val
      })
      localStorage.setItem("cartList", JSON.stringify(state.carlist))
    },
    remove(state, item) {
      state.carlist.forEach((element, index) => {
        if (element.good._id == item._id) {
          state.carlist.splice(index, 1)
        }
      })
      localStorage.setItem("cartList", JSON.stringify(state.carlist))
    }
  },
  getters: {
    allPrice(state) {
      var sum = 0;
      state.carlist.forEach((element) => {
        sum += element.good.salePrice * element.num
      })
      return sum
    },
    // price(state) {
    //   var num = 0
    //   state.carlist.forEach(element => {
    //     num+= element.good.        
    //   });
    // }
  },
  actions: {
  },
  modules: {
  }
})
